package com.BookManager.controller;

import com.BookManager.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class BookController {

    @Resource
    BookService bookService;

    @GetMapping("/books")
    public String books(Model model){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        model.addAttribute("nickname",user.getUsername());
        model.addAttribute("books",bookService.getBookMap());
        return "books";
    }

    @GetMapping("/addBook")
    public String addBook(Model model){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        model.addAttribute("nickname",user.getUsername());
        return "addBook";
    }

    @PostMapping("/addBook")
    public String addBook(String title,String info, double price){
        bookService.addBook(title,info,price);
        return "redirect:/books";
    }

    @GetMapping("/deleteBook")
    public String deleteBook(int bid){
        bookService.deleteBook(bid);
        return "redirect:/books";
    }

}
